package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class ReceivableServlet
 */
@WebServlet(urlPatterns = { "/Receivable", "/receivable", "/ReceivableServlet", "/receivableServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class ReceivableServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public ReceivableServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<ReceivableModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				response.sendRedirect("receivableNew.jsp");
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			ReceivableModel query = new ReceivableModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<ReceivableModel, ReceivableModelExt> dal = new GenericDal<ReceivableModel, ReceivableModelExt>(new ReceivableModel());

			ReceivableModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("receivable", obj);
				getServletContext().getRequestDispatcher("/receivableEdit.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			ReceivableModel query = new ReceivableModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<ReceivableModel, ReceivableModelExt> dal = new GenericDal<ReceivableModel, ReceivableModelExt>(new ReceivableModel());

			ReceivableModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("receivable", obj);
				response.sendRedirect("receivableView.jsp");

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			ReceivableModel obj = new ReceivableModel();

			// SET NAME here

			GenericDal<ReceivableModel, ReceivableModelExt> dal = new GenericDal<ReceivableModel, ReceivableModelExt>(new ReceivableModel());
			int res = 0;

			try {
				String strName = request.getParameter("name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("receivable", "" + res);
					out.println(resultXML);
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		} else if (mode.equalsIgnoreCase("delete")) {

			ReceivableModel query = new ReceivableModel();
			String id = request.getParameter("id");
			String url="";
			String idProject = request.getParameter("idProject");
			if (idProject != null && !idProject.isEmpty()) {
				url="?idProject="+idProject;
			}
			query.setId(Integer.parseInt(id));

			GenericDal<ReceivableModel, ReceivableModelExt> dal = new GenericDal<ReceivableModel, ReceivableModelExt>(new ReceivableModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				response.sendRedirect("receivableList.jsp"+url);
			} else {
				// TODO fail
				PrintWriter out = response.getWriter();
				out.println("Cannot delete!");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {

			ReceivableModel obj = new ReceivableModel();
//String id_company = request.getParameter("id_company");
//                    if (id_company != null && !id_company.isEmpty()) {
//					    obj.setIdCompany(Integer.parseInt(id_company));
//                    }
//
//String id_phase = request.getParameter("id_phase");
//                    if (id_phase != null && !id_phase.isEmpty()) {
//					    obj.setIdPhase(Integer.parseInt(id_phase));
//                    }


String plan_date_date = request.getParameter("plan_date_date");
    String plan_date_time = request.getParameter("plan_date_time");
    if (plan_date_date != null && !plan_date_date.isEmpty() && plan_date_time != null && !plan_date_time.isEmpty()) {
            obj.setPlanDate(DateTimeUtil.parseDateTime(plan_date_date, plan_date_time));
} else {
    obj.setPlanDate(DateTimeUtil.parseDate(plan_date_date));
}


String real_date_date = request.getParameter("real_date_date");
    String real_date_time = request.getParameter("real_date_time");
    if (real_date_date != null && !real_date_date.isEmpty() && real_date_time != null && !real_date_time.isEmpty()) {
            obj.setRealDate(DateTimeUtil.parseDateTime(real_date_date, real_date_time));
} else {
    obj.setRealDate(DateTimeUtil.parseDate(real_date_date));
}

String name = request.getParameter("name");
					obj.setName(name);

//String code = request.getParameter("code");
//					obj.setCode(code);
//
//String status = request.getParameter("status");
//                    if (status != null && !status.isEmpty()) {
//					    obj.setStatus(Integer.parseInt(status));
//                    }
//
//String notification = request.getParameter("notification");
//                    if (notification != null && !notification.isEmpty()) {
//					    obj.setNotification(Integer.parseInt(notification));
//                    }



String id_project = request.getParameter("id_project");
                    if (id_project != null && !id_project.isEmpty()) {
					    obj.setIdProject(Integer.parseInt(id_project));
                    }

String description = request.getParameter("description");
					obj.setDescription(description);

//String remark = request.getParameter("remark");
//					obj.setRemark(remark);
//
//String receivable_type = request.getParameter("receivable_type");
//                    if (receivable_type != null && !receivable_type.isEmpty()) {
//					    obj.setReceivableType(Integer.parseInt(receivable_type));
//                    }

String money = request.getParameter("money");
                    if (money != null && !money.isEmpty()) {
					    obj.setMoney(Double.parseDouble(money));
                    }

String currency = request.getParameter("currency");
                    if (currency != null && !currency.isEmpty()) {
					    obj.setCurrency(Integer.parseInt(currency));
                    }

			obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<ReceivableModel, ReceivableModelExt> dal = new GenericDal<ReceivableModel, ReceivableModelExt>(new ReceivableModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res > 0) {
					// TODO : success, refresh cache and redirect to somewhere
					String urlIdProject = "receivableList.jsp?idProject=" + obj.getIdProjectToString();
					response.sendRedirect(urlIdProject);
				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("receivable", obj);
				getServletContext().getRequestDispatcher("/receivableInput.jsp").forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			ReceivableModel query = new ReceivableModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<ReceivableModel, ReceivableModelExt> dal = new GenericDal<ReceivableModel, ReceivableModelExt>(new ReceivableModel());

			ReceivableModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				
				//String id_company = request.getParameter("id_company");
//              if (id_company != null && !id_company.isEmpty()) {
//				    obj.setIdCompany(Integer.parseInt(id_company));
//              }
//
//String id_phase = request.getParameter("id_phase");
//              if (id_phase != null && !id_phase.isEmpty()) {
//				    obj.setIdPhase(Integer.parseInt(id_phase));
//              }


String plan_date_date = request.getParameter("plan_date_date");
String plan_date_time = request.getParameter("plan_date_time");
if (plan_date_date != null && !plan_date_date.isEmpty() && plan_date_time != null && !plan_date_time.isEmpty()) {
      obj.setPlanDate(DateTimeUtil.parseDateTime(plan_date_date, plan_date_time));
} else {
obj.setPlanDate(DateTimeUtil.parseDate(plan_date_date));
}


String real_date_date = request.getParameter("real_date_date");
String real_date_time = request.getParameter("real_date_time");
if (real_date_date != null && !real_date_date.isEmpty() && real_date_time != null && !real_date_time.isEmpty()) {
      obj.setRealDate(DateTimeUtil.parseDateTime(real_date_date, real_date_time));
} else {
obj.setRealDate(DateTimeUtil.parseDate(real_date_date));
}

String name = request.getParameter("name");
				obj.setName(name);

//String code = request.getParameter("code");
//				obj.setCode(code);
//
//String status = request.getParameter("status");
//              if (status != null && !status.isEmpty()) {
//				    obj.setStatus(Integer.parseInt(status));
//              }
//
//String notification = request.getParameter("notification");
//              if (notification != null && !notification.isEmpty()) {
//				    obj.setNotification(Integer.parseInt(notification));
//              }



String id_project = request.getParameter("id_project");
              if (id_project != null && !id_project.isEmpty()) {
				    obj.setIdProject(Integer.parseInt(id_project));
              }

String description = request.getParameter("description");
				obj.setDescription(description);

//String remark = request.getParameter("remark");
//				obj.setRemark(remark);
//
//String receivable_type = request.getParameter("receivable_type");
//              if (receivable_type != null && !receivable_type.isEmpty()) {
//				    obj.setReceivableType(Integer.parseInt(receivable_type));
//              }

String money = request.getParameter("money");
              if (money != null && !money.isEmpty()) {
				    obj.setMoney(Double.parseDouble(money));
              }

String currency = request.getParameter("currency");
              if (currency != null && !currency.isEmpty()) {
				    obj.setCurrency(Integer.parseInt(currency));
              }

				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success
						String urlIdProject = "receivableList.jsp?idProject=" + obj.getIdProjectToString();
						response.sendRedirect(urlIdProject);
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("receivable", obj);
					getServletContext().getRequestDispatcher("/receivableList.jsp").forward(request, response);
				}
			} else {
				// TODO data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			ReceivableModel obj = new ReceivableModel();

			// SET NAME here

			GenericDal<ReceivableModel, ReceivableModelExt> dal = new GenericDal<ReceivableModel, ReceivableModelExt>(new ReceivableModel());
			int res = 0;

			try {
				String strName = request.getParameter("name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("receivable", "" + res);
					out.println(resultXML);
				}
				else
				{
					//TODO: respone something
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		}
	}

}